from time import sleep
from lxml import etree
from tool.allure_ import allure_step_no
from tool.screenshot import capture_screenshot


class DwFail(Exception):
    pass

path=r'D:\jb\tu\app'
def jt(case_name, positioning_instructions):
    print('定位元素不存在，进行截图')
    info = f'用例标题{case_name}，定位元素说明：{positioning_instructions}'
    capture_screenshot(info)


def find_elements(dv, element, positioning_method, case_name, positioning_instructions):
    '''
    :param dv: 设备对象
    :param element:元素定位数据
    :param positioning_method:元素定位方式
    :param case_name:测试用例名称
    :param positioning_instructions: 这个元素测试的对象说明
    :return:
    '''
    # allure_step_no(f'用例-{case_name}-步骤{positioning_instructions}-开始定位')
    sleep(1.5)
    if positioning_method == 'xpath':
        try:
            if dv.xpath(element).exists:
                print('定位成功')
                allure_step_no(f'用例-{case_name}--步骤--{positioning_instructions}--定位成功')
                return dv.xpath(element)
            else:
                jt(case_name, positioning_instructions)
                allure_step_no(f'用例--{case_name}--步骤--{positioning_instructions}--定位失败进行截图保存--{path}')
                raise DwFail(f'定位失败,用例标题{case_name}，定位元素说明：{positioning_instructions}')

        except etree.XPathEvalError:
            jt(case_name, positioning_instructions)
            allure_step_no(f'用例--{case_name}--步骤--{positioning_instructions}--定位失败进行截图保存--{path}')
            raise DwFail(f'xpath路径错误定位,用例标题{case_name}，定位元素说明：{positioning_instructions}')

    elif positioning_method == 'text':
        if dv(text=element).exists:
            allure_step_no(f'用例-{case_name}--步骤--{positioning_instructions}--定位成功')
            return dv(text=element)
        else:
            jt(case_name, positioning_instructions)
            allure_step_no(f'用例--{case_name}--步骤--{positioning_instructions}--定位失败进行截图保存--{path}')
            raise DwFail(f'定位失败,用例标题{case_name}，定位元素说明：{positioning_instructions}')
    else:
        print('暂时只支持xpath，text定位')


if __name__ == '__main__':
    from devices import dv
    # find_elements(dv, '.ViewGroup[2]', 'xpath', 'xpath', '点击设12222211111111置')
    find_elements(dv, '//*[@resource-id="com.visteon.txzing.accountcenter:id/feedback_record_bar_time', 'xpath',
                  '进行录音问题反馈', '点击语音条').click()
    # find_elements(dv, '//*[@resource-id="com.visteon.txzing.accountcenter:id/mine_feedback_recyclerview"]/android.view.ViewGroup[1]/android.view.ViewGroup[1]', 'xpath',
    #               '进行录音问题反馈', '点击语音条').click()
